from django.db import models
from project_nav.models import Satellite


class SatelliteSchedule(models.Model):
    """
    卫星排程信息模型
    """
    satellite = models.ForeignKey(
        Satellite,
        on_delete=models.CASCADE,
        related_name='schedules',
        verbose_name='卫星'
    )
    
    schedule_info = models.JSONField(
        verbose_name='排程信息',
        help_text='存储任务块的详细信息，包括任务名称、持续时间、需要设备总体、设备容量、每日设备配置、开始时间和结束时间等'
    )
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '卫星排程'
        verbose_name_plural = '卫星排程'
        db_table = 'satellite_schedule'
        ordering = ['-updated_at']
    
    def __str__(self):
        return f'{self.satellite.name} - 排程信息'
    
    def get_task_count(self):
        """获取任务块数量"""
        if isinstance(self.schedule_info, list):
            return len(self.schedule_info)
        elif isinstance(self.schedule_info, dict) and 'tasks' in self.schedule_info:
            return len(self.schedule_info['tasks'])
        return 0
    
    def get_total_duration(self):
        """获取总持续时间"""
        total_duration = 0
        if isinstance(self.schedule_info, list):
            for task in self.schedule_info:
                if isinstance(task, dict) and 'duration' in task:
                    total_duration += int(task.get('duration', 0))
        elif isinstance(self.schedule_info, dict) and 'tasks' in self.schedule_info:
            for task in self.schedule_info['tasks']:
                if isinstance(task, dict) and 'duration' in task:
                    total_duration += int(task.get('duration', 0))
        return total_duration
